package com.qyhl.school.school.reporter.sign;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolListBean;
import com.qyhl.webtv.commonlib.utils.ninephotolayout.BGASortableNinePhotoLayout;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SCHOOL_REPORTER_SIGN)
public class SchoolReportSignActivity extends BaseActivity
        implements SchoolReportSignContract.SchoolReportSignView, BGASortableNinePhotoLayout.Delegate {
    @BindView(R2.id.name)
    EditText name;
    @BindView(R2.id.phone)
    EditText phone;
    @BindView(R2.id.sex)
    RadioGroup sex;
    @BindView(R2.id.age)
    EditText age;
    @BindView(R2.id.school)
    TextView school;
    @BindView(R2.id.NinePhotoLayout)
    BGASortableNinePhotoLayout NinePhotoLayout;

    /**
     * 上传token
     */
    private UpTokenBean mUpToken;
    /**
     * 图片多选
     */
    public static final int CHOOSE_REQUEST = 200;

    public static final int RESULT_REQUEST = 202;

    /**
     * 图片数据
     */
    private List<LocalMedia> selectedList = new ArrayList<>();

    private List<SchoolListBean> schoolList = new ArrayList<>();

    private SchoolReportSignPresenter mPresenter;

    private String upName;

    private String upPhone;

    private String upSchoolName;

    private int upSex = 2;

    private int upAge = 0;

    private int upSchoolId = 0;

    private String username;

    @Override
    protected int getContentView() {
        return R.layout.activity_school_reporter_sign;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(true).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new SchoolReportSignPresenter(this);

        username = CommonUtils.getInstance().getUserName();
        //九宫格设置监听
        NinePhotoLayout.setDelegate(this);

        mPresenter.getToken(false);
    }

    @Override
    protected void setListener() {
        sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.sex_male) {
                    upSex = 1;
                } else {
                    upSex = 2;
                }
            }
        });

    }

    private void checkData() {
        upName = name.getText().toString();
        if (StringUtils.isEmpty(upName)) {
            showToast("请填写姓名！");
            dismissLoading();
            return;
        }

        upPhone = phone.getText().toString();
        if (!StringUtils.isMobileNO(upPhone)) {
            showToast("请填写正确的手机号！");
            dismissLoading();
            return;
        }


        if (StringUtils.isEmpty(age.getText().toString())) {
            showToast("请填写年龄！");
            dismissLoading();
            return;
        }
        upAge = Integer.parseInt(age.getText().toString());


        if (upSchoolId == 0) {
            upSchoolName = school.getText().toString();
            if (StringUtils.isEmpty(upSchoolName)) {
                showToast("请选择学校！");
                dismissLoading();
                return;
            }
        } else {
            upSchoolName = "";
        }


        if (selectedList == null || selectedList.size() < 1) {
            showToast("请上传证件照！");
            dismissLoading();
        } else {
            if (mUpToken == null) {
                mPresenter.getToken(true);
                return;
            }
            List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
            for (int i = 0; i < selectedList.size(); i++) {
                LocalMedia image = selectedList.get(i);
                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(2);
                videoCoverBean.setPath(image.getCompressPath());
                videoCoverBean.setPostion(0);
                uploadBeans.add(videoCoverBean);
            }
            QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getToken(), mUpToken.getPrefix(), new UploadResultListener() {
                @Override
                public void uplaodError() {
                    dismissLoading();
                    showToast("上传证件照出错!");
                }

                @Override
                public void uploadSuccess(List<UploadBean> files) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < files.size(); i++) {
                        if (i == files.size() - 1) {
                            stringBuilder.append(files.get(i).getUrl());
                        } else {
                            stringBuilder.append(files.get(i).getUrl()).append(",");
                        }
                    }
                    mPresenter.doSign(username, upName, upSex, upPhone, upAge, upSchoolId, upSchoolName, stringBuilder.toString());
                }

                @Override
                public void uploadPre(double percent) {

                }
            });
        }
    }

    @Override
    public void signResult(boolean isSuccess, String msg) {
        dismissLoading();
        showToast(msg);
        if (isSuccess) {
            finish();
        }
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        mUpToken = data;
        if (isUpload) {
            checkData();
        }
    }

    @Override
    public void getTokenError(boolean isUpload) {
        if (isUpload) {
            dismissLoading();
            showToast("申请失败！");
        }
    }

    @OnClick({R2.id.back_btn, R2.id.school, R2.id.post_btn})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.school) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("list", (Serializable) schoolList);
            ARouter.getInstance()
                    .build(ARouterPathConstant.SCHOOL_REPORTER_SIGN_SCHOOL)
                    .withBundle("bundle",bundle)
                    .navigation(SchoolReportSignActivity.this,RESULT_REQUEST);
        } else if (id == R.id.post_btn) {
            showLoading();
            checkData();
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        PictureSelector.create(SchoolReportSignActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(true)
                .enableCrop(true)
                .freeStyleCropEnabled(true)
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)
                .withAspectRatio(1, 1)
                .selectionMedia(selectedList)
                // 小于100kb的图片不压缩
                .minimumCompressSize(200)
                .forResult(CHOOSE_REQUEST);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        for (int i = 0; i < selectedList.size(); i++) {
            if (selectedList.get(i).getCompressPath().equals(NinePhotoLayout.getData().get(position))) {
                selectedList.remove(i);
            }
        }

        NinePhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        MNImageBrowser.showImageBrowser(this, view, position, models);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_REQUEST:
                if (data != null && data.getExtras() != null) {
                    schoolList = (List<SchoolListBean>) data.getExtras().getSerializable("list");
                    for (int i = 0; i < schoolList.size(); i++) {
                        if (schoolList.get(i).isSelected()) {
                            upSchoolId = schoolList.get(i).getId();

                            if (upSchoolId == 0) {
                                upSchoolName = data.getExtras().getString("name");
                                school.setText(upSchoolName);
                            } else {
                                school.setText(schoolList.get(i).getName());
                            }
                        }
                    }
                }
                break;
            case CHOOSE_REQUEST:
                List<LocalMedia> resultList = PictureSelector.obtainMultipleResult(data);
                if (resultList != null && resultList.size() > 0) {
                    selectedList.clear();
                    selectedList.addAll(resultList);
                }
                ArrayList<String> select = new ArrayList<>();

                for (int i = 0; i < selectedList.size(); i++) {
                    select.add(selectedList.get(i).getCompressPath());
                }

                NinePhotoLayout.setData(select);
                break;
        }
    }

}
